/*
 * Copyright (C) 2016 Nishant Srivastava
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package github.nisrulz.easydeviceinfo.base;

import ohos.account.app.AppAccount;
import ohos.account.app.AppAccountAbility;
import ohos.agp.components.webengine.WebView;
import ohos.app.Context;
import ohos.security.SystemPermission;
import ohos.security.permission.NeedsPermission;

import java.util.List;

/**
 * EasyId Mod Class
 *
 * @since 2021-06-10
 */
public class EasyIdMod {
    private final Context context;
    private final AppAccountAbility appAccountAbility;

    /**
     * Instantiates a new Easy id mod.
     *
     * @param context the context
     */
    public EasyIdMod(final Context context) {
        this.context = context;
        appAccountAbility = new AppAccountAbility(context);
    }

    /**
     * Get ohos accounts
     * <p>
     * You need to declare the below permission in the manifest file to use this properly
     * <p>
     * SystemPermission.MANAGE_LOCAL_ACCOUNTS
     *
     * @return the string [ ]
     */
    @NeedsPermission(SystemPermission.MANAGE_LOCAL_ACCOUNTS)
    public final String[] getAccounts() {
        String[] result = null;
        if (PermissionUtil.hasPermission(context,
            SystemPermission.MANAGE_LOCAL_ACCOUNTS)) {
            List<AppAccount> accounts = appAccountAbility.getAllAccessibleAccounts();
            if (accounts != null) {
                result = new String[accounts.size()];
                for (int i = 0; i < accounts.size(); i++) {
                    result[i] = accounts.get(i).getName();
                }
            }
        }
        return CheckValidityUtil.checkValidData(result);
    }

    /**
     * Gets ua.
     *
     * @return the ua
     */
    public final String getUA() {
        final String systemUa = System.getProperty("http.agent");
        String result = new WebView(context).getWebConfig().getUserAgent() + "_" + systemUa;
        return CheckValidityUtil.checkValidData(result);
    }
}
